#!/usr/bin/perl -w

# The MIT License
#
# Copyright (c) 2008 Comcast Interactive Media
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# cim.sf.core.command.sh client script
# See cim.sf.core.command.sh.CommandServer for protocol documentation.
#
# Author: Jeremy Volkman <jeremy_volkman@cable.comcast.com>

use strict;
use IO::Socket;
use IO::Select;
use Fcntl;
use FindBin qw($Bin);
use Cwd;

# param check
die "Not enough parameters" if $#ARGV < 2;

my $cwd    = cwd;
my $key    = read_key();
my $status = 1;            # cim.sf.core.command.Command.ERROR_GENERAL = 1

my $sock = new IO::Socket::INET(
    PeerAddr => $ARGV[0],
    PeerPort => $ARGV[1],
    Proto    => 'tcp',
);

# verify socket is open
die "ERROR: Could not connect to command server: $!\n" unless $sock;

# install SIGPIPE handler
$SIG{PIPE} = \&catch_pipe;

# Switch socket and stdin to non-blocking mode
nonblock( $sock );

my %wbuf = ( $sock => '', STDOUT => '', STDERR => '' );
my %rbuf = ( $sock => '' );
my $buf;
my $fh;
my $blocksize = 32768;

# fill socket write buffer with initial output
# send the client identifier
$wbuf{$sock} .= 'SCMD';

# and the key
$wbuf{$sock} .= "$key\0";

# and the working dir
$wbuf{$sock} .= "$cwd\0";

# send the command line:
# <command>\0[arg1]\0[arg2]\0...[argN]\0\0
$wbuf{$sock} .= "$ARGV[2]\0";
my $stdin = 0;
foreach ( @ARGV[ 3 .. $#ARGV ] ) {
    if ( $_ eq '-' ) {
        $stdin = 1;
    }
    $wbuf{$sock} .= "$_\0";
}
$wbuf{$sock} .= "\0";

my $rs = IO::Select->new();
my $ws = IO::Select->new();
$ws->add($sock);
my $commandSent = 0;

while ( scalar $rs->handles > 0 || scalar $ws->handles > 0 ) {
    IO::Select->select( $rs, $ws, undef );
    foreach $fh ( $rs->can_read(0) ) {
        # socket/stdin input
        my $r_rs = sysread( $fh, $buf, $blocksize );
        die $! unless defined($r_rs);
        if ( $r_rs == 0 ) {
            $rs->remove($fh);
            $ws->add($sock) if ( $fh == \*STDIN );
        }
        else {
            if ( $fh == $sock ) {
                $rbuf{$fh} .= $buf;
                while ( ( length $rbuf{$sock} ) >= 5 ) {
                    my $textlen = unpack 'N', substr( $rbuf{$sock}, 1, 4 );
                    if ( length $rbuf{$sock} >= 5 + $textlen ) {
                        # full output block, print to specified stream
                        my $text   = substr( $rbuf{$sock}, 5, $textlen );
                        my $s_type = substr( $rbuf{$sock}, 0, 1 );
                        if ( $s_type eq 'O' || $s_type eq 'E' ) {
                            my $stream = ( $s_type eq 'O' ) ? \*STDOUT : \*STDERR;
                            $wbuf{$stream} .= $text;
                            $ws->add($stream) if ( length $wbuf{$stream} > 0 );
                        }
                        elsif ( $s_type eq 'S' ) {
                            # status code
                            $status = $text;
                        }
                        $rbuf{$sock} = substr( $rbuf{$sock}, $textlen + 5 );
                    }
                    else {
                        last;
                    }
                }
            }
            else {    
                #stdin
                $wbuf{$sock} .= $buf;
                $ws->add($sock);
            }
        }
    }

    foreach $fh ( $ws->can_write(0) ) {
        # sock/stdout/stderr output
        my $w_rs = syswrite( $fh, $wbuf{$fh}, $blocksize );
        die $! unless defined($w_rs);
        $wbuf{$fh} = substr( $wbuf{$fh}, $w_rs );
        if ( length $wbuf{$fh} == 0 ) {
            $ws->remove($fh);
            if ( $fh == $sock ) {
                if ( !$commandSent ) {
                    $commandSent = 1;
                    $rs->add($sock);
                    $rs->add( \*STDIN ) if $stdin;
                }
                elsif ( !$rs->exists( \*STDIN ) ) {
                    # if stdin is removed from read select, it's been fully read.
                    # so shutdown outbound
                    shutdown( $sock, 1 );
                }
            }
        }
    }
}

# cleanup socket
close $sock;
exit $status;

# function to switch stream to non-blocking mode
sub nonblock {
    foreach (@_) {
        my $flags = fcntl( $_, F_GETFL, 0 ) or die $!;
        fcntl( $_, F_SETFL, $flags | O_NONBLOCK ) or die $!;
    }
}

sub read_key {
    # read key file
    my $term = $/;
    undef $/;
    open( KEYFILE, "<$Bin/.key" ) or die "ERROR: Could not open key file: $!\n";
    my $key = <KEYFILE>;
    close(KEYFILE);
    $/ = $term;
    return $key;
}

sub catch_pipe {
    close $sock;
    exit 1;
}